package cn.edu.hrbcu.es.invigilatemanagerment.configuration;

import cn.edu.hrbcu.es.invigilatemanagerment.dao.TeacherMapper;
import cn.edu.hrbcu.es.invigilatemanagerment.pojo.Teacher;
import cn.edu.hrbcu.es.invigilatemanagerment.pojo.TeacherExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class DBUserDetailsManager implements UserDetailsManager, UserDetailsPasswordService {
    @Autowired
    TeacherMapper teacherMapper;

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    @Override
    public void createUser(UserDetails user) {
        Teacher teacher = new Teacher(null,null,null,null,null,null,null,null,null);
        teacher.setUsername(user.getUsername());
        teacher.setPassword(user.getPassword());
        teacher.setIsPresent(1);
        teacherMapper.insert(teacher);
    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }

    /**
     * 通过用户名称，从数据库中获取用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TeacherExample example = new TeacherExample();
        TeacherExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<Teacher> teacheres = teacherMapper.selectByExample(example);

        if(teacheres != null && teacheres.size() > 0){
            // 空的角色
            Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

            Teacher theTeacher = teacheres.get(0);
            return new User(theTeacher.getUsername(),
                    theTeacher.getPassword(),
                    theTeacher.getIsPresent() == 1 ? true : false,
                    true,
                    true,
                    true,
                    authorities);
        }else{
            throw new UsernameNotFoundException(username);
        }
    }
}
